package com.janlei.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class CloneUtils {

    public static Object deepCopy(Object obj) throws IOException {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
        } catch (IOException e) {
            e.printStackTrace();
        }

        byte[] x = bos.toByteArray();
        System.out.println("len:" + x.length);
        for (int i = 0; i < x.length; i++) {
            System.out.print(x[i]);
        }
        // 从流内读出对象
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(
                    new ByteArrayInputStream(bos.toByteArray())
            );
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            return ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            bos.close();
            oos.close();
            ois.close();
        }

        return null;
    }
}
